﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObject.Database;
using System.Drawing;

public partial class Pages_Reports_IncomeReport : System.Web.UI.Page
{
    enum GroupName
    {
        BoatID = 0,
        ReservationCode = 1,
        GuestID = 2,
        DepartureDate = 3,
        IsShuttle = 4,
        SubTotal = 5,
        Deposit = 6,
        Paid = 7,
        Balance = 8,
        Average = 9
    }

    const string _groupName = "BoatID+ReservationCode+GuestID+DepartureDate+IsShuttle+SubTotal+Deposit+Paid+Balance+Average";
    const string url = @"/Pages/Reports/IncomeReport.aspx?AgentID={0}&BoatID={1}&ClientType={2}&PaidMethod={3}&FromDate={4:d}&ToDate={5:d}&SortField={6}&SortOption={7}";

    private GridViewHelper helper;

    #region Fields & Properties
    private DateTime? _fromDate, _toDate;
    private string _agentID, _boatID;
    private int _clientType, _paidMethod;

    private int PageIndex
    {
        get
        {
            if (Request["page"] != null)
            {
                return int.Parse(Request["page"].ToString());
            }
            return 1;
        }
    }
    #endregion

    #region Methods

    /// <summary>
    /// Load Boats
    /// </summary>
    private void LoadBoats()
    {
        // Load Boats
        var boatList = DataObject.DataAccess.BoatDAO.CreateInstant().GetAllBoats();
        boatList.Insert(0, new BoatEntity() { BoatName = "All boats", BoatID = String.Empty });

        this.ddlBoat.DataSource = boatList;
        this.ddlBoat.DataTextField = "BoatName";
        this.ddlBoat.DataValueField = "BoatID";
        this.ddlBoat.DataBind();

        this.ddlPaidMethod.DataSource = new string[] { "All", "Mr Linh" }.Concat(DropDownListHelper.PaymentMethods);
        this.ddlPaidMethod.DataBind();
    }

    /// <summary>
    /// 
    /// </summary>
    private void GetQueryString()
    {
        // ClientType
        this._clientType = -1;
        if (Request["ClientType"] != null) Int32.TryParse(Request["ClientType"], out _clientType);
        ddlClientType.SelectedValue = this._clientType.ToString();

        this._agentID = (Request["AgentID"] != null ? Request["AgentID"] : String.Empty);
        this.txtAgentID.Text = _agentID;

        this._boatID = (Request["BoatID"] != null ? Request["BoatID"] : String.Empty);
        this.ddlBoat.SelectedValue = _boatID;

        this._paidMethod = (Request["PaidMethod"] != null ? int.Parse(Request["PaidMethod"]) : 0);
        this.ddlPaidMethod.SelectedIndex = this._paidMethod;

        DateTime fromDate, toDate;

        // FromDate
        this._fromDate = DateTime.Today;
        if (DateTime.TryParse(Request["FromDate"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDate))
        {
            this._fromDate = fromDate.Date;
        }

        this.txtFromDate.Text = _fromDate.Value.ToShortDate();

        // ToDate
        // FromDate
        this._toDate = DateTime.Today;
        if (DateTime.TryParse(Request["ToDate"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out toDate))
        {
            this._toDate = toDate.Date;
        }

        this.txtToDate.Text = _toDate.Value.ToShortDate();
    }

    /// <summary>
    /// 
    /// </summary>
    private void GetOnForm()
    {
        DateTime fromDate, toDate;
        // FromDate
        if (DateTime.TryParse(txtFromDate.Text, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDate))
            this._fromDate = fromDate.Date;
        else
            this._fromDate = DateTime.Now;

        // ToDate
        if (DateTime.TryParse(txtToDate.Text, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out toDate))
            this._toDate = toDate.Date;
        else
            this._toDate = DateTime.Now;

        // Client Type
        this._clientType = Int32.Parse(this.ddlClientType.SelectedValue);
        this._boatID = this.ddlBoat.SelectedValue;
        this._paidMethod = this.ddlPaidMethod.SelectedIndex;
        this._agentID = this.txtAgentID.Text;
    }

    /// <summary>
    /// Search method
    /// </summary>
    private void Search()
    {
        int count = 0;
        BuildOnGrid(out count, PageIndex, define.PageSize);

        smartPager.PageSize = define.PageSize;
        smartPager.QueryStringKey = "page";
        smartPager.RowCount = count;
        smartPager.UrlFormatString = String.Concat(String.Format(url, _agentID, _boatID, _clientType, _paidMethod, _fromDate, _toDate), "&page={0}");
        smartPager.Visible = count > define.PageSize;
    }

    private void BuildOnGrid(out int count)
    {
        BuildOnGrid(out count, null, null);
    }

    private void BuildOnGrid(out int count, int? pageIndex, int? pageSize)
    {
        HashSet<string> hs = new HashSet<string>();
        hs.Add("DepartureDate ASC");
        hs.Add("ReservationCode ASC");
        hs.Add("PaymentDate ASC");

        IList<ViewPaymentReport> collection = DataObject.DataAccess.ReservationDAO.CreateInstant().GetViewIncomeReport(_fromDate, _toDate, _clientType, _paidMethod, _boatID, _agentID, pageIndex, pageSize, out count, hs);

        helper = new GridViewHelper(this.grv);
        helper.RegisterGroup(_groupName.Split('+'), true, true);
        helper.RegisterSummary("TotalAmt", SummaryOperation.Sum);
        helper.RegisterSummary("TotalAmt", SummaryOperation.Sum, _groupName);
        //helper.RegisterSummary("SubTotal", SummaryOperation.Sum);
        //helper.RegisterSummary("Balance", SummaryOperation.Sum);
        helper.GroupHeader += new GroupEvent(helper_GroupHeader);
        helper.GroupSummary += new GroupEvent(helper_GroupSummary);

        grv.DataSource = collection;
        grv.DataBind();
    }

    /// <summary>
    /// Print method
    /// </summary>
    private void Print()
    {
        int count = 0;
        BuildOnGrid(out count);

        var form = new System.Web.UI.HtmlControls.HtmlForm();
        form.Controls.Add(grv); // gvParent là gridview 

        string attachment = String.Format("attachment; filename=payment{0:yyyyMMdd}.xls", DateTime.Now);
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        Response.Charset = String.Empty;
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

        System.IO.StringWriter stw = new System.IO.StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        this.Controls.Add(form);
        form.RenderControl(htextw);

        Response.Write(stw.ToString());
        Response.End();
    }
    #endregion

    #region Events

    /// <summary>
    /// Page Load
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.LoadBoats();

            // Process Searching
            this.GetQueryString();
            this.Search();
        }
    }

    /// <summary>
    /// Button Find
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        GetOnForm();
        Response.Redirect(String.Concat(String.Format(url, _agentID, _boatID, _clientType, _paidMethod, _fromDate, _toDate)));
    }

    /// <summary>
    /// Button Print
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReport_Click(object sender, EventArgs e)
    {
        this.GetQueryString();
        this.Print();
    }
    #endregion

    private void helper_GroupHeader(string groupName, object[] values, GridViewRow row)
    {
        if (groupName == _groupName)
        {
            row.BackColor = Color.FromName("#ffdf51");
            row.Cells[0].Text = "(" + ((DateTime)values[(int)GroupName.DepartureDate]).ToShortDateString() + ")&nbsp;&nbsp;<b>Booking code: " + values[(int)GroupName.ReservationCode] + "</b>&nbsp;&nbsp;[ Boat:  " + values[(int)GroupName.BoatID] + " ]";
        }
    }

    private void helper_GroupSummary(string groupName, object[] values, GridViewRow row)
    {
        if (groupName == _groupName)
        {
            row.BackColor = Color.FromName("#fff6cd");

            decimal subTotal = Convert.ToDecimal(values[(int)GroupName.SubTotal]);
            decimal deposit = Convert.ToDecimal(values[(int)GroupName.Deposit]);
            decimal paid = Convert.ToDecimal(values[(int)GroupName.Paid]);
            decimal balance = subTotal - deposit - paid;
            row.Cells[0].HorizontalAlign = HorizontalAlign.Right;
            row.Cells[0].Text = String.Format(
                "<div style=\"font-family: Courier New\">" +
                "<div><b>SubTotal: {0}</b></div>" +
                "<div>Deposit: {1}</div>" +
                "<div>Paid: {2}</div>" +
                "<hr />" +
                "<div><b>Balance: {3}</b></div>",
                subTotal.ToString("#,##0.##").PadLeft(12, "&nbsp;"),
                deposit.ToString("#,##0.##").PadLeft(12, "&nbsp;"),
                paid.ToString("#,##0.##").PadLeft(12, "&nbsp;"),
                balance.ToString("#,##0.##").PadLeft(12, "&nbsp;"));
        }
    }
}